package com.woniuxy.enjoylife.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniuxy.enjoylife.configuration.AlipayConfig;
import com.woniuxy.enjoylife.entity.Goods_order;
import com.woniuxy.enjoylife.entity.Server_order;
import com.woniuxy.enjoylife.entity.dto.ReturnServerOrderDto;
import com.woniuxy.enjoylife.mapper.Goods_orderMapper;
import com.woniuxy.enjoylife.mapper.Server_orderMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
public class AliPayController {

//    @Resource
//    private AlipayClient alipayClient;
//    @Resource
//    private AlipayTradePagePayRequest alipayRequest;

    @Resource
    private Server_orderMapper serverOrderMapper;
    @Resource
    private Goods_orderMapper goodsOrderMapper;


    @RequestMapping("/pay")
    @ResponseBody
    public void pay(@RequestBody ReturnServerOrderDto dto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("支付宝");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);//跳转到商户指定页面
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);//请求商户的接口：修改订单状态

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = dto.getSerial();
        //付款金额，必填
        String total_amount = dto.getPrice().toString();
        //订单名称，必填   将订单号作为订单的名称
        String subject = dto.getServername();
        //商品描述，可空
        String body = dto.getDescribe();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求  result 支付成功的页面
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出  显示支付成功的页面
        try {
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/result")
    public void result(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //调用SDK验证签名
        if (signVerified) {//验证成功
            //商户订单号
//            String out_trade_no = request.getParameter("out_trade_no");
//            //支付宝交易号
//            String trade_no = request.getParameter("trade_no");
//            //交易状态
//            String trade_status = request.getParameter("trade_status");

            System.out.println("签名验证成功");

        } else {//验证失败
            response.getWriter().println("fail");
            System.out.println("签名验证失败");

        }

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");


        //通过订单号out_trade_no去修改订单状态
//        OrderService orderService= new OrderServiceImpl();
//        ResponseResult responseResult =orderService.changeStatus(out_trade_no,trade_status);

        if (out_trade_no.contains("ELGO")){
            goodsOrderMapper.updateOrder(new Goods_order().setSerial(out_trade_no).setResult(3));
        }
        if (out_trade_no.contains("ELSO")){
            serverOrderMapper.update(new Server_order().setSerial(out_trade_no).setResult(5));
        }

    }


}


